package com.bw.util;

import com.alibaba.fastjson.JSONObject;
import com.bw.common.GmallConfig;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;

import java.io.IOException;
import java.util.ArrayList;

/**
 * 上海大数据学院
 * 项目规划及管理：李剑
 * 技术指导及需求分析：郭洵
 * 编程：楚志高
 *
 * @author bawei  bigdata sh
 * @since 2021-06-11
 */
public class HBaseUtil {
    //初始化连接
    private static Connection connection=null;
    //连接方法
    public static Connection getConnection(String zkQuorum, String port) throws Exception {
        //存储hbase的连接诶地址
        Configuration conf = HBaseConfiguration.create();
        //zookeeper的集群地址
        conf.set("hbase.zookeeper.quorum", zkQuorum);
        //zookeeper的端口
        conf.set("hbase.zookeeper.property.clientPort", port);

        try {
            connection = ConnectionFactory.createConnection(conf);
        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;
    }

    public static void closeHbaseCon(Connection connection){
        if (connection!=null){
            try {
                connection.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Connection conn = HBaseUtil.getConnection(ConfigUtil.getZookeeperQuorum(), ConfigUtil.getZookeeperClientPort());

        Admin admin=null;

        try {
            //获取hbase执行权限
            admin = conn.getAdmin();
            NamespaceDescriptor d1 = NamespaceDescriptor.create(GmallConfig.HBASE_SCHEMA).build();
            admin.createNamespace(d1);
            //构建表描述器
            TableDescriptorBuilder newBuilder = TableDescriptorBuilder.newBuilder(TableName.valueOf("GMALL2022_REALTIME:aaa"));
            //定义空集合来存储列族描述符
            ArrayList<ColumnFamilyDescriptor> listColumns = new ArrayList<>();
            ColumnFamilyDescriptor cfd_info = ColumnFamilyDescriptorBuilder.newBuilder("Order_Detail".getBytes()).build();
            ColumnFamilyDescriptor cfd_res = ColumnFamilyDescriptorBuilder.newBuilder("Transaction".getBytes()).build();
            listColumns.add(cfd_info);
            listColumns.add(cfd_res);
            newBuilder.setColumnFamilies(listColumns);
            TableDescriptor descriptor = newBuilder.build();
            admin.createTable(descriptor);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            HBaseUtil.closeHbaseCon(connection);
        }
    }
}
